#!/user/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Sjy
Description: 模块管理器
"""

from typing import Dict, Type
from .base import BaseModule
from .extreme_load import ExtremeLoadModule
from .repair_scheme import RepairSchemeModule
from .repair_scheme_strength import RepairSchemeStrengthModule
from .database import DatabaseModule
from .repair_scheme_digital_twin import RepairSchemeDigitalTwinModule
from .tools import Tools
import gui.controls.envs as envs


class ModuleManager:
    """模块管理器（单例模式）"""

    _instance = None
    _initialized = False

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(ModuleManager, cls).__new__(cls)
        return cls._instance

    def __init__(self):
        if not self._initialized:
            self._initialized = True
            self._modules = []
            self._old_category = None
            self._module_manager = None
            self._modules_keys = {}
            self._init_modules()

    def _init_modules(self):
        """初始化所有模块"""
        # 极限载荷
        extreme_load_module = ExtremeLoadModule()
        # 维修方案优化
        repair_scheme_module = RepairSchemeModule()
        # 维修方案强度分析
        repair_scheme_strength_module = RepairSchemeStrengthModule()
        # 维修方案数字孪生试验验证
        repair_scheme_digital_twin_module = RepairSchemeDigitalTwinModule()
        # 数据库
        database_module = DatabaseModule()
        # 工具
        tools_module = Tools()

        self._modules = [
            {
                "title": "极限受载分析模块",
                "module": extreme_load_module,
            },
            {
                "title": "维修方案优化模块",
                "module": repair_scheme_module,
            },
            {
                "title": "维修方案强度分析模块",
                "module": repair_scheme_strength_module,
            },
            {
                "title": "维修方案数字孪生试验验证模块",
                "module": repair_scheme_digital_twin_module,
            },
            {
                "title": "数据库",
                "module": database_module,
            },
            {
                "title": "工具",
                "module": tools_module,
            },
        ]

        for module in self._modules:
            self._modules_keys[module["title"]] = module["module"]

        # 极限受载分析需要根据 exe 运行获取相关提示信息
        extreme_load_module.reg_exe_tips()

    def get_module(self, title: str) -> BaseModule:
        """获取指定模块"""
        return [module for module in self._modules if module["title"] == title][0][
            "module"
        ]

    def get_all_modules(self) -> Dict[str, BaseModule]:
        """获取所有模块"""
        return self._modules

    def init_module_toolbar(self, ribbon=None):
        """初始化所有模块的工具栏"""
        for item in self._modules:
            module = item["module"]
            if hasattr(module, "init_category"):
                category = module.init_category(ribbon=ribbon)
                if not self._old_category:
                    self._old_category = category  # 默认第一个模块

    def get_old_category(self):
        """获取旧的模块"""
        return self._old_category

    def changed_ribbonbar_category(self, ribbon, params):
        """切换模块"""
        title = params.get("currentTitle", "")
        if title == "维修方案数字孪生试验验证模块":
            params.get("setCategory")(self.old_category)
            self._modules_keys.get(title).to_localhost()
            return
        self.old_category = params.get("category", None)
        envs.ipimas_update_modular_tree({"categoryTitle": title})

    def init_dock(self, tree, params) -> None:
        categoryTitle = params.get("categoryTitle", "")
        for item in self._modules:
            title = item["title"]
            module = item["module"]
            if title == categoryTitle and hasattr(module, "init_dock"):
                module.init_dock(tree)
                break


# 导出单例实例
module_manager = ModuleManager()
